<template>
    <div>
        <van-nav-bar title="我买的" left-arrow @click-left="onClickLeft">
            <template #right>
                <van-icon name="search" size="18" @click="search()" />
            </template>
        </van-nav-bar>
        <van-search v-model="value" v-show="searchShow" placeholder="请输入搜索关键词" @search="onSearch" />
        <van-tabs v-model="active" @click="activeClick">
            <van-tab title="全部">
                <van-pull-refresh v-model="refreshingall" @refresh="onRefresh(99)">
                    <van-list v-model="loadingall" :finished="finishedall" finished-text="没有更多了" @load="onLoad(99)"
                        :immediate-check="false">
                        <van-card :price="item.paid_fee" :desc="item.description" :title="item.title"
                            :thumb="item.cover" v-for="(item, index) in listall" :key="index" @click.stop="toView(item.type,item.order_info_id)">
                            <template #bottom>
                                <div class="priceBottom red" v-if="item.paid == 1">已签收</div>
                                <div class="priceBottom red" v-if="item.paid == 2">已购买</div>
                                <div class="priceBottom red" v-if="item.paid == 3">退款完结</div>
                                <div class="priceBottom red" v-if="item.paid == 0">待支付</div>
                            </template>
                            <template #footer>
                                <van-button round size="small" v-if="item.paid == 2 || item.paid==1 || item.paid==0" @click="gokefuchat(item.id)">联系客服</van-button>
                                <van-button round size="small" v-if="item.paid == 2" @click.stop="todrawback(item.id)">退款
                                </van-button>
                                <van-button round size="small" v-if="item.paid == 1" plain type="danger"
                                    @click.stop="toevaluate(item.id,item.order_info_id,item.type)">去评价</van-button>
                                <van-button round size="small" v-if="item.paid == 3" @click.stop="deleterecord()">删除记录
                                </van-button>
                                <van-button round size="small" plain type="danger" v-if="item.paid == 0" @click.stop="conpay(item.id)">继续付款</van-button>
                            </template>
                        </van-card>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
            <van-tab title="待付款">
                <van-pull-refresh v-model="refreshingdfk" @refresh="onRefresh(0)">
                    <van-list v-model="loadingdfk" :finished="finisheddfk" finished-text="没有更多了" @load="onLoad(0)"
                        :immediate-check="false">
                        <van-card :price="item.paid_fee" :desc="item.description" :title="item.title"
                            :thumb="item.cover" v-for="(item, index) in listdfk" :key="index" @click.stop="toView(item.type,item.order_info_id)">
                            <!-- <template #bottom>
                        <div class="priceBottom">物流详情：</div>
                    </template> -->
                            <template #footer>
                                <van-button round size="small" @click.stop="gokefuchat(item.id)">联系客服</van-button>
                                <van-button round size="small" plain type="danger" @click.stop="conpay(item.id)">继续付款</van-button>
                            </template>
                        </van-card>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
            <van-tab title="待收货">
                <van-pull-refresh v-model="refreshingdsh" @refresh="onRefresh(2)">
                    <van-list v-model="loadingdsh" :finished="finisheddsh" finished-text="没有更多了" @load="onLoad(2)"
                        :immediate-check="false">
                        <van-card :price="item.paid_fee" :desc="item.description" :title="item.title"
                            :thumb="item.cover" v-for="(item, index) in listdsh" :key="index" @click.stop="toView(item.type,item.order_info_id)">
                            <template #bottom>
                                <div class="priceBottom">详情：你可以观看该视频了，注意当你观看后就不能退款了</div>
                            </template>
                            <template #footer>
                                <van-button round size="small" @click.stop="gokefuchat(item.id)">联系客服</van-button>
                                <van-button round size="small" @click.stop="todrawback(item.id)">退款</van-button>
                                <van-button round size="small" plain type="danger" @click.stop="confirm(item.id)">确认收货</van-button>
                            </template>
                        </van-card>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
            <van-tab title="待评价">
                <van-pull-refresh v-model="refreshingdpj" @refresh="onRefresh(1)">
                    <van-list v-model="loadingdpj" :finished="finisheddpj" finished-text="没有更多了" @load="onLoad(1)"
                        :immediate-check="false">
                        <van-card :price="item.paid_fee" :desc="item.description" :title="item.title"
                            :thumb="item.cover" v-for="(item, index) in listdpj" :key="index" @click.stop="toView(item.type,item.order_info_id)">
                            <template #bottom>
                                <div class="priceBottom red">已签收</div>
                            </template>
                            <template #footer>
                                <van-button round size="small" @click.stop="gokefuchat(item.id)">联系客服</van-button>
                                <van-button round size="small" plain type="danger" @click.stop="toevaluate(item.id,item.order_info_id,item.type)">去评价
                                </van-button>
                            </template>
                        </van-card>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
            <van-tab title="退款">
                <van-pull-refresh v-model="refreshingtk" @refresh="onRefresh(3)">
                    <van-list v-model="loadingtk" :finished="finishedtk" finished-text="没有更多了" @load="onLoad(3)"
                        :immediate-check="false">
                        <van-card :price="item.paid_fee" :desc="item.description" :title="item.title"
                            :thumb="item.cover" v-for="(item, index) in listtk" :key="index" @click.stop="toView(item.type,item.order_info_id)">
                            <template #price>
                                <div>退款￥20.30</div>
                            </template>
                            <template #bottom>
                                <div class="priceBottom red">退款成功</div>
                            </template>
                            <template #footer>
                                <van-button round size="small" @click.stop="deleterecord()">删除记录</van-button>
                                <van-button round plain type="danger" size="small" @click.stop="seedetails()">查看详情
                                </van-button>
                            </template>
                        </van-card>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
        </van-tabs>
        <van-action-sheet v-model="show" title="确定收到货了吗">
            <img :src="url" alt="" />
            <div class="content">为了保障你的权益，请收到商品确认无误后在确认收货</div>
            <van-button class="notarize" @click="confirmsh">确认</van-button>
        </van-action-sheet>
    </div>
</template>
<script>
import { Dialog } from 'vant';
export default {
    data() {
        return {
            value: '',
            active: 0,
            show: false,
            url: 'https://img01.yzcdn.cn/vant/ipad.jpeg',
            searchShow: false,
            orderlistall: '',
            orderlistdfk: '',
            orderlistdsh: '',
            orderlistdpj: '',
            orderlisttk: '',
            pageall: 1,
            listall: [],
            pagedfk: 1,
            listdfk: [],
            pagedsh: 1,
            listdsh: [],
            pagedpj: 1,
            listdpj: [],
            pagetk: 1,
            listtk: [],
            loadingall: true,
            finishedall: false,
            refreshingall: false,
            totalall: '',
            loadingdfk: true,
            finisheddfk: false,
            refreshingdfk: false,
            totaldfk: '',
            loadingdsh: true,
            finisheddsh: false,
            refreshingdsh: false,
            totaldsh: '',
            loadingdpj: true,
            finisheddpj: false,
            refreshingdpj: false,
            totaldpj: '',
            loadingtk: true,
            finishedtk: false,
            refreshingtk: false,
            totaltk: '',
            idsh:''
        };
    },
    mounted() {
        this.active = Number(this.$route.query.active);
        this.onLoad(99);
        this.onLoad(0);
        this.onLoad(2);
        this.onLoad(1);
        this.onLoad(3);
    },
    methods: {
        //联系客服按钮
        gokefuchat(orderid) {
            console.log(orderid);
            this.$router.push({ name: "kefuchat",query:{orderid}});
        },
        //左上角返回按钮
        onClickLeft() {
            this.$router.push({ name: 'my' });
        },
        //查看退款查看详情
        seedetails() {
            this.$router.push({ name: 'refund', query: { active: 0 } });
        },
        //跳转退款中心
        todrawback(id) {
            this.$router.push({ name: 'drawback', query: { id } });
        },
        //跳转评价页面
        toevaluate(order_id,id,type) {
            this.$router.push({ name: 'evaluate',query:{order_id,id,type}});
        },
        //确认收货
        confirm(id) {
            this.show = true;
            this.idsh=id;
        },
        //删除记录
        deleterecord() {
            Dialog.confirm({
                title: '确定删除记录？'
            }).then(() => {
                    // on confirm
                    console.log("这个接口还没写");
                })
                .catch(() => {
                    // on cancel
                    console.log("这个接口还没写");
                });
        },
        //搜索
        search() {
            this.searchShow = true;
        },
        onSearch() {
            localStorage.setItem('ordersearchdata',this.value);
            this.$router.push({
                name: 'ordersearchlist',
                params: {
                    searchdata:this.value
                }
            });
            setTimeout(()=>{
                this.$router.replace({name:'frontrefresh'});
            },50);        
         },
        async getOrderList(paid) {
            let query = {
                paid,
                page: 1,
                limit: 2,
                keyword: ''
            };
            
            switch (paid) {
                case 99: //全部订单
                    query.page = this.pageall;
                    let resall = await this.$frontaxios.post(this.$front.getOrderList, query);
                    console.log(resall);
                    if (resall.code == 1) {
                        this.loadingall = true;
                        this.orderlistall = resall.data.orderlist;
                        this.totalall = resall.data.total;
                    } else {
                        this.orderlistall=[];
                        console.log('没有获取到全部的订单');
                    }
                    break;
                case 0: //待付款订单
                    query.page = this.pagedfk;
                    let resdfk = await this.$frontaxios.post(this.$front.getOrderList, query);
                    console.log(resdfk);
                    if (resdfk.code == 1) {
                        this.loadingdfk = true;
                        this.orderlistdfk = resdfk.data.orderlist;
                        this.totaldfk = resdfk.data.total;
                    } else {
                        this.orderlistdfk=[];
                        console.log('没有获取到待付款的订单');
                    }
                    break;
                case 2: //待收货订单
                    query.page = this.pagedsh;
                    let resdsh = await this.$frontaxios.post(this.$front.getOrderList, query);
                    if (resdsh.code == 1) {
                        this.loadingdsh = true;
                        this.orderlistdsh = resdsh.data.orderlist;
                        this.totaldsh = resdsh.data.total;
                    } else {
                        this.orderlistdsh=[];
                        console.log('没有获取到待收货的订单');
                    }
                    break;
                case 1: //待评价订单
                    query.page = this.pagedpj;
                    let resdpj = await this.$frontaxios.post(this.$front.getOrderList, query);
                    if (resdpj.code == 1) {
                        this.loadingdpj = true;
                        this.orderlistdpj = resdpj.data.orderlist;
                        this.totaldpj = resdpj.data.total;
                    } else {
                        this.orderlistdpj=[];
                        console.log('没有获取到待评价的订单');
                    }
                    break;
                case 3: //退款完成订单
                    query.page = this.pagetk;
                    let restk = await this.$frontaxios.post(this.$front.getOrderList, query);
                    console.log(restk)
                    if (restk.code == 1) {
                        this.loadingtk = true;
                        this.orderlisttk = restk.data.orderlist;
                        this.totaltk = restk.data.total;
                        console.log(this.orderlisttk,this.totaltk);
                    } else {
                        this.loadingtk=false;
                        console.log('没有获取到退款完成的订单');
                    }
                    break;
            }
        },
        async onLoad(paid) {
            switch (paid) {
                case 99: //全部显示
                    if (this.refreshingall) {
                        this.listall = [];
                        this.refreshingall = false;
                    }
                    await this.getOrderList(99);
                    this.listall.push(...this.orderlistall);
                    this.pageall++;
                    this.loadingall = false; //不加载了，滚动底会变为true
                    if (this.listall.length >= this.totalall) {
                        this.finishedall = true; //数据全部加载完设为true
                    }
                    break;
                case 0: //待付款
                    if (this.refreshingdfk) {
                        this.listdfk = [];
                        this.refreshingdfk = false;
                    }
                    await this.getOrderList(0);
                    this.listdfk.push(...this.orderlistdfk);
                    this.pagedfk++;
                    this.loadingdfk = false; //不加载了，滚动底会变为true
                    if (this.listdfk.length >= this.totaldfk) {
                        this.finisheddfk = true; //数据全部加载完设为true
                    }
                    break;
                case 2:
                    if (this.refreshingdsh) {
                        this.listdsh = [];
                        this.refreshingdsh = false;
                    }
                    await this.getOrderList(2);
                    this.listdsh.push(...this.orderlistdsh);
                    this.pagedsh++;
                    this.loadingdsh = false; //不加载了，滚动底会变为true
                    if (this.listdsh.length >= this.totaldsh) {
                        this.finisheddsh = true; //数据全部加载完设为true
                    }
                    break;
                case 1:
                    if (this.refreshingdpj) {
                        this.listdpj = [];
                        this.refreshingdpj = false;
                    }
                    await this.getOrderList(1);
                    this.listdpj.push(...this.orderlistdpj);
                    this.pagedpj++;
                    this.loadingdpj = false; //不加载了，滚动底会变为true
                    if (this.listdpj.length >= this.totaldpj) {
                        this.finisheddpj = true; //数据全部加载完设为true
                    }
                    break;
                case 3:
                    if (this.refreshingtk) {
                        this.listtk = [];
                        this.refreshingtk = false;
                    }
                    await this.getOrderList(3);
                    console.log(this.orderlisttk);
                    this.listtk=[]
                    this.listtk.push(...this.orderlisttk);
                    this.pagetk++;
                    this.loadingtk = false; //不加载了，滚动底会变为true
                    if (this.listtk.length >= this.totaltk) {
                        this.finishedtk = true; //数据全部加载完设为true
                    }
                    break;
            }
        },
        onRefresh(paid) {
            switch (paid) {
                case 99:
                    // 清空列表数据
                    this.finishedall = false;

                    // 重新加载数据
                    // 将 loadingall 设置为 true，表示处于加载状态
                    this.loadingall = true;
                    this.pageall = 1;
                    this.onLoad(99);
                    this.$toast.success('刷新成功');
                    break;
                case 0:
                    // 清空列表数据
                    this.finisheddfk = false;

                    // 重新加载数据
                    // 将 loadingdfk 设置为 true，表示处于加载状态
                    this.loadingdfk = true;
                    this.pagedfk = 1;
                    this.onLoad(0);
                    this.$toast.success('刷新成功');
                    break;
                case 2:
                    // 清空列表数据
                    this.finisheddsh = false;

                    // 重新加载数据
                    // 将 loadingdsh 设置为 true，表示处于加载状态
                    this.loadingdsh = true;
                    this.pagedsh = 1;
                    this.onLoad(2);
                    this.$toast.success('刷新成功');
                    break;
                case 1:
                    // 清空列表数据
                    this.finisheddpj = false;

                    // 重新加载数据
                    // 将 loadingdpj 设置为 true，表示处于加载状态
                    this.loadingdpj = true;
                    this.pagedpj = 1;
                    this.onLoad(1);
                    this.$toast.success('刷新成功');
                    break;
                case 3:
                    // 清空列表数据
                    this.finishedtk = false;

                    // 重新加载数据
                    // 将 loadingtk 设置为 true，表示处于加载状态
                    this.loadingtk = true;
                    this.pagetk = 1;
                    this.onLoad(3);
                    this.$toast.success('刷新成功');
                    break;
            }
        },
        activeClick(type){
            switch(type){
                case 0:
                  this.loadingall = true;
                  this.finishedall = false;
                  this.listall=[];
                  this.pageall=1;
                  this.onLoad(99);
                break;
                case 1:
                  this.loadingdfk = true;
                  this.finisheddfk = false;
                  this.listdfk=[];
                  this.pagedfk=1;
                  this.onLoad(0);
                break;
                case 2:
                  this.loadingdsh = true;
                  this.finisheddsh = false;
                  this.listdsh=[];
                  this.pagedsh=1;
                  this.onLoad(2);
                break;
                case 3:
                  this.loadingdpj = true;
                  this.finisheddpj = false;
                  this.listdpj=[];
                  this.pagedpj=1;
                  this.onLoad(1);
                break;
                case 4:
                  this.loadingtk = true;
                  this.finishedtk = false;
                  this.listdtk=[];
                  this.pagedtk=1;
                  this.onLoad(3);
                break;
            }
        },
        toView(type,id){
             if(type=='column'){
                    this.$router.push({name:"product",query:{id}});
             }else if(type=='exam'){
                    this.$router.push({ name:'examcontent',query:{id,columnid:'order'}});
             }else if(type=='video'){
                    this.$router.push({ name: 'videocontent', query: { id,columnid:'order'}});
             }else if(type=='audio'){
                    this.$router.push({ name: 'audiocontent', query: { id,columnid:'order'}});
             }else if(type=='image_text'){
                    this.$router.push({ name: 'image_textcontent', query: { id,columnid:'order'}});
             }
        },
        confirmsh(){
           this.$dialog.confirm({
              title: '确认收货',
              message: '确认收货吗，确认后将不能退款？',
             })
            .then(async () => {
                   let id=this.idsh;
                   let res=await this.$frontaxios.post(this.$front.confirmSh,{id});
                   if(res.code==1){
                      this.$toast.success('确认收货成功');
                      this.show=false;
                      setTimeout(() => {
                            this.listdsh=[];
                            this.pagedsh=1;
                            this.onLoad(2);
                      }, 300);
                    }else{
                      this.$toast.fail('确认收货失败');
                    }
               })
              .catch(() => {
                   // on cancel
             });
          
        },
        async conpay(id){
            // if(isWeixin()){
            let res=await this.$frontaxios.post(this.$front.getIdOrder,{id});
            console.log(res);
            // if(res.code==0){
                let randcode=res.data.randcode;
                let total_fee=res.data.paid_fee;
                let ordernumber=res.data.order_no;
                this.payOrder(randcode,total_fee,ordernumber) 
            // }else{
            //     this.$toast.fail('可能订单已经超时，请重新下单');
            // }
            // }else{
            //    this.$dialog.alert({title:"温馨提示",message:"请在微信中付款"});
            // }
        },
        async payOrder(randcode,total_fee,ordernumber) {
				let body='您花了'+total_fee+'买了订单号'+ordernumber+'的商品';
				if (isWeixin()) {
                   let res = await this.$frontaxios.post(this.$front.getWeiXinPayData,{total_fee,ordernumber,body,randcode});
				   console.log(res);
				   if(res.code==1){
				   let data=res.data.weixinpaydata;
				   this.callpay(data);
				   }else{
                    this.$toast.fail('可能订单已经超时，请重新下单再来付款');
					console.log('没有获得支付数据参数')
				   }
				} else {
					alert("请在微信里打开支付");
				}
			},
			jsApiCall(data) {
				var that=this;
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', data,
					function(res) {
						WeixinJSBridge.log(res.err_msg);
						console.log('err_code:'+res.err_code+'err_desc:'+res.err_desc+'err_msg:'+res.err_msg);
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							//alert("支付成功!");
							clearInterval(that.stime);
							that.$toast.success("支付成功");
							that.$router.push({name: 'product',query: {id:that.id}});
						} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
							that.$toast.success("用户取消支付!");
						} else {
							that.$toast.success("支付失败!");
						}
					}
				);
			},
			callpay(data) {
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.jsApiCall(data), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.jsApiCall(data));
						document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall(data));
					}
				} else {
					this.jsApiCall(data);
				}
			}
    }
};
</script>
<style scoped>
/* .listClass {
    width: 100%;
    height: 100vh;
    overflow-y: auto;
} */

.van-button {
    padding: 0 1rem 0 1rem;
}

.priceBottom {
    background-color: #EEE;
    border-radius: 2px;
    padding-left: 5px;
}

.content {
    padding: 16px 16px 50px;
}

img {
    width: 98px;
}

.van-action-sheet__content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.notarize {
    width: 90%;
    border-radius: 1rem;
    background-color: #ee8c33;
    color: #fff;
}

.red {
    color: red;
}
</style>
